<div style="position:relative;padding-left:5px;height:20px;padding-top:4px;margin:0;background-color:#ece9d8;">
	<input type="checkbox" onClick="showAbnormalResultsOnly(this.checked)" /> Show Abnormal Results Only
</div>

<div id="testsContainer" style="overflow:auto;position:relative;float:left;height:420px;width:99%;">
	<div id="chartContainer" style="overflow:auto;width:100%;height:200px;">
		<div id="graphLegend" style="float:right;width:99%;height:10%;overflow:auto;"></div>
		<div id="graphChart" style="float:left;width:99%;height:75%;overflow:auto;"></div>
	</div>
	<div id="commentsTree" style="overflow:auto;width:100%;"></div>
</div>

<script>
var graphChart = null;
var chartData = {};
var minDate = null;
var maxDate = null;

function showAbnormalResultsOnly(state) {
	resultsGrid.forEachRow(function(rowId){
		if (resultsGrid.cells(rowId,4).getValue().toLowerCase() == "abnormal") {
			resultsGrid.setRowHidden(rowId,state);
		}
	});
}

var colorList = new Array();
colorList[colorList.length] = "#FF0000"; // Red
colorList[colorList.length] = "#008000"; // Green
colorList[colorList.length] = "#0000FF"; // Blue
colorList[colorList.length] = "#FFFF00"; // Yellow
colorList[colorList.length] = "#FFA500"; // Orange
colorList[colorList.length] = "#FF4500"; // OrangeRed
colorList[colorList.length] = "#FFC0CB"; // Pink
colorList[colorList.length] = "#800080"; // Purple
colorList[colorList.length] = "#A52A2A"; // Brown
colorList[colorList.length] = "#00FFFF"; // Cyan
colorList[colorList.length] = "#D2691E"; // Chocolate
colorList[colorList.length] = "#FF7F50"; // Coral
colorList[colorList.length] = "#FFD700"; // Gold
colorList[colorList.length] = "#FF00FF"; // Fuchsia
colorList[colorList.length] = "#EE82EE"; // Violet
colorList[colorList.length] = "#FF00FF"; // Magenta
colorList[colorList.length] = "#800000"; // Maroon

function getColor(index) {
	if (index < 0 || index > colorList.length-1) {
		return null;
	}
	return colorList[index];
}

var testLayout = new dhtmlXLayoutObject("testsContainer", "3E");
testLayout.setImagePath("<?=$this->baseUrl?>/img/");
testLayout.cells("a").hideHeader();
var resultsGrid = testLayout.cells("a").attachGrid();
testLayout.cells("a").setHeight('160');
testLayout.cells("b").setText('<?=__('Graph')?>');
testLayout.cells("b").attachObject("chartContainer");
testLayout.cells("b").setHeight('250');
testLayout.cells("b").collapse();
testLayout.cells("c").setText('<?=__('Comments')?>');
testLayout.cells("c").attachObject("commentsTree");
testLayout.setEffect('collapse',true);
testLayout.setEffect("resize",true);

resultsGrid.setImagePath("<?=$this->baseUrl?>/img/");
resultsGrid.setHeader('<?=__('Test Name')?>,<?=__('Value')?>,<?=__('Unit')?>,<?=__('Ref. Range')?>,<?=__('Abnormal')?>,<?=__('Status')?>,');
resultsGrid.setInitWidths("*,*,*,*,60,50,0");
resultsGrid.setColTypes("ro,ro,ro,ro,ro,ro,ro");
resultsGrid.setSkin("xp");
resultsGrid.init();
resultsGrid.load('<?=$this->baseUrl?>/lab-results.raw/results.json?patientId='+mainController.getActivePatient()+'&dateBegin='+TabState.getParam('dateBegin')+'&dateEnd='+TabState.getParam('dateEnd'),onPostLoad,"json");
function onPostLoad() {
	numRows = resultsGrid.getRowsNum();
	if (numRows <= 0) {
		return;
	}
	var firstRowId = resultsGrid.getRowId(0);
	var lastRowId = resultsGrid.getRowId(numRows - 1);
	var userData = resultsGrid.cells2(numRows-1,6).getValue();
	userData = userData.split("::");
	minDate = userData[0];
	userData = resultsGrid.cells2(0,6).getValue();
	userData = userData.split("::");
	maxDate = userData[0];

	var oMinDate = dojo.date.stamp.fromISOString(minDate);
	var oMaxDate = dojo.date.stamp.fromISOString(maxDate);
	var comparison = dojo.date.compare(oMinDate,oMaxDate);
	if (comparison > 0) {
		var tmpDate = minDate;
		minDate = maxDate;
		maxDate = tmpDate;
	}
}

resultsGrid.attachEvent('onRowSelect',onRowSelected);
function onRowSelected(rowId,cellIndex) {
}

var resultsMenu = new dhtmlXMenuObject('resultsColumnMenu','standard');
resultsMenu.setImagePath("<?=$this->baseUrl?>/img/");
resultsMenu.renderAsContextMenu();
resultsMenu.setOpenMode("web");
resultsMenu.attachEvent('onClick',resultsOnMenuClicked);
function resultsOnMenuClicked(itemId,type) {
	switch (itemId) {
		case 'add_to_graph':
			addSelectedResultsToChart();
			break;
		case 'clear_graph':
			clearChart();
			break;
	}
}

function clearChart() {
	dojo.setInnerHTML(dojo.byId('graphLegend'),'');
	dojo.setInnerHTML(dojo.byId('graphChart'),'');
	chartData = new Array();
}

function addSelectedResultsToChart() {
	var rowIds = resultsGrid.getSelectedRowId();
	if (rowIds == null) {
		alert('<?=__('No lab selected/')?>');
		return;
	}

	var hAxis = new Array();
	var vAxis = new Array();

	var needRedraw = false;
	rowIds = rowIds.split(',');
	for (var key in rowIds) {
		rowId = rowIds[key];
		if (rowId in chartData) {
			// Selected lab already in the graph
			continue;
		}

		needRedraw = true;
		// retrieve all the results having the same Test Name
		var testName = resultsGrid.cells(rowId,0).getValue();
		resultsGrid.forEachRow(function(id){
			var userData = null;
			if (hAxis.length <= resultsGrid.getRowsNum()) {
				userData = resultsGrid.cells(id,6).getValue();
				userData = userData.split("::");
				hAxis[hAxis.length] = userData[0];
				//vAxis[vAxis.length] = userData[1];
			}

			if (resultsGrid.cells(id,0).getValue() == testName && !(id in chartData)) {
				if (userData == null) {
					var userData = resultsGrid.cells(id,6).getValue();
					userData = userData.split("::");
				}
				chartData[id] = {xTxt:userData[0],yTxt:userData[1],name:testName};
			}
		});
	}

	if (!needRedraw) {
		alert('<?=__('Selected labs already in the graph')?>');
		return;
	}

	hAxis.sort();
	//vAxis.sort(function(a,b){return(a-b);}); // numeric sort in ascending order

	var hasVZero = false;
	var uniqueNames = new Array('');
	var itemList = new Array();
	for (var rowId in chartData) {
		var name = chartData[rowId].name;
		var inArray = false;
		for (x in uniqueNames) {
			if (uniqueNames[x] == name) {
				indexName = x;
				inArray = true;
				break;
			}
		}
		if (!inArray) {
			indexName = uniqueNames.length;
			uniqueNames[indexName] = name;
		}

		var xTxt = chartData[rowId].xTxt;
		//var origTxt = xTxt;
		//var tmpTxt = xTxt.split('-');
		//xTxt = tmpTxt[1] + '/' + tmpTxt[2] + '/' + tmpTxt[0];
		var inArray = false;
		for (x in hAxis) {
			if (hAxis[x] == xTxt) {
				xVal = x;
				inArray = true;
				break;
			}
		}
		if (!inArray) {
			xVal = hAxis.length;
			hAxis[xVal] = xTxt;
		}

		var yTxt = chartData[rowId].yTxt;
		inArray = false;
		for (x in vAxis) {
			if (vAxis[x] == yTxt) {
				yVal = x;
				inArray = true;
				break;
			}
		}
		if (!inArray) {
			yVal = vAxis.length;
			vAxis[yVal] = yTxt;
		}
		if (yTxt == '0') {
			hasVZero = true;
		}

		itemList[itemList.length] = {xLabel:xTxt,yLabel:yTxt,name:name};
	}

	if (!hasVZero) {
		vAxis[vAxis.length] = '0';
	}
	vAxis.sort(function(a,b){return(a-b);}); // numeric sort in ascending order

	if (graphChart != null) {
		graphChart.destroy();
		graphChart = null;
	}

	var arrPlots = new Array();
	var defaultSeries = new Array();
	defaultSeries[defaultSeries.length] = "{x:0,y:"+(vAxis.length-1)+"}";
	defaultSeries[defaultSeries.length] = "{x:0,y:0}";
	defaultSeries[defaultSeries.length] = "{x:"+(hAxis.length-1)+",y:0}";
	arrPlots[0] = {name:"imaginary",seriesName:"Imaginary Plot",series:defaultSeries};

	var arrSeries = new Array();
	var xLabel = '';
	var yLabel = '';
	var testName = '';
	var itemKey = 0;
	var xKey = 0;
	var yKey = 0;
	var nameKey = 0;
	var origItemList = itemList;
	for (xKey in hAxis) {
		xIndex = xKey;
		// get all items with the horizontal values
		for (itemKey in itemList) {
			yIndex = -1;
			if (itemList[itemKey].xLabel == hAxis[xKey]) {
				yLabel = itemList[itemKey].yLabel;
				// locate the position/index of the yLabel in the vAxis
				for (yKey in vAxis) {
					if (vAxis[yKey] == yLabel) {
						yIndex = yKey;
						break;
					}
				}
				testName = itemList[itemKey].name;
				delete itemList[itemKey]; // remove to speed up the loops
				// if could not locate the vertical index, just continue
				if (yIndex == -1) {
					continue;
				}

				// find the index given the test name
				for (nameKey in uniqueNames) {
					if (uniqueNames[nameKey] == testName) {
						break;
					}
				}

				if (!(nameKey in arrPlots)) {
					arrPlots[nameKey] = {name:"default"+nameKey,seriesName:testName,series:new Array(),};
				}
				arrPlots[nameKey].series[arrPlots[nameKey].series.length] = "{x:"+xIndex+",y:"+yIndex+"}";
			}
		}
	}

	var arrXLabels = new Array();
	for (xKey in hAxis) {
		var tmpTxt = hAxis[xKey].split('-');
		xTxt = tmpTxt[1] + '/' + tmpTxt[2] + '/' + tmpTxt[0];
		arrXLabels[arrXLabels.length] = '{value:'+xKey+',text:"'+xTxt+'"}';
	}
	var arrYLabels = new Array();
	for (yKey in vAxis) {
		arrYLabels[arrYLabels.length] = '{value:'+yKey+',text:"'+vAxis[yKey]+'"}';
	}

	//itemList.sort(sortByXAxis);

	oGraphChart = dojo.byId('graphChart');
	oGraphLegend = dojo.byId('graphLegend');
	dojo.setInnerHTML(oGraphChart,'');
	dojo.setInnerHTML(oGraphLegend,'');
	graphChart = new custom.Chart2D("graphChart");

	var graphLegend = '';
	var plots = new Array();
	for (var i in arrPlots) {
		var plot = arrPlots[i];
		if (plot.name == "imaginary") {
			eval('plots[plots.length] = {name:"'+plot.name+'",seriesName:"'+plot.seriesName+'",series:['+plot.series.join(',')+'],color:"gray",markers:false};');
		}
		else {
			var color = getColor(i);
			eval('plots[plots.length] = {name:"'+plot.name+'",seriesName:"'+plot.seriesName+'",series:['+plot.series.join(',')+'],color:"'+color+'"};');
			graphLegend += '<label style="color:'+color+'">'+plot.seriesName+'</label> ';
		}
	}
	eval('var plotData = {xLabels:['+arrXLabels.join(',')+'],yLabels:['+arrYLabels.join(',')+'],plots:plots};');
	graphChart.createGraph(plotData);
	dojo.setInnerHTML(oGraphLegend,graphLegend);
}

function sortByXAxis(a,b) {
	return strSort(a.x,b.x);
}

function strSort(a,b) {
	//return a.localeCompare(b);
	if (a < b) {
		return -1;
	}
	else if (a > b) {
		return 1;
	}
	else {
		return 0;
	}
}

resultsMenu.loadXML('<?=$this->baseUrl?>/lab-results.xml/menu.xml');

resultsGrid.enableContextMenu(resultsMenu);
resultsGrid.enableMultiselect(true);

comTree = new dhtmlXTreeObject("commentsTree","100%","100%",0);
comTree.setImagePath("<?=$this->baseUrl?>/img/");
comTree.insertNewChild(0,1,'Comments');
comTree.insertNewChild(1,11,'Latest');
comTree.closeAllItems();

</script>
